import {
    request,
    WXshowToast,
    WXRedirectTo,
    WXNavigateTo
} from '../../utils/index.js';
import {
    Api,
    getWXPayOptions,
    requestPayment
} from '../../config/api.js';
const appInst = getApp();
const {
    imgBaseUrl,
    host,
    color
} = appInst.globalData;

Page({
    data: {
        imgBaseUrl,
        host,
        color,
        addressList: [],
        // 默认地址
        addr: {},
        // [羊币，微信]
        payway: [true, false],
        goodlist: null,
        goodNum: null,
        totalMoney: 0, //总价格
        remaining: 0, //剩余羊币
        deduction: 0 //抵扣羊币 
    },
    onLoad: function (options) {
    },


    onShow: function () {
        this.getGood()
        this.sleep_coin()
        if (wx.getStorageSync('gmtype')) { //如果有商品类型 则写入页面
            this.setData({
                gmtype: wx.getStorageSync('gmtype')
            })
            wx.removeStorageSync('gmtype')
        }
        if (wx.getStorageSync('dzactive')) { //获取选中的地址 如没选中则调用默认收货地址
            let dzactive = wx.getStorageSync('dzactive')
            console.log(dzactive)
            this.setData({
                addr: dzactive
            })
            this.freight()
            wx.removeStorageSync('dzactive')
        } else { //否则调用默认收货地址
            this._getAddressList()
        }

    },

    // 获取商品想详情
    getGood() {
        let goodlist = wx.getStorageSync("goodlist");
        let totalMoney = 0
        let goodNum = 0
        if (this.data.gmtype == 2) {
            goodlist.forEach((item) => {
                goodNum += item.num
            })
        } else {
            goodNum = 1
        }

        this.setData({
            goodlist,
            goodNum
        })
    },




    // 计算 scroll-view 高度
    calcScrollViewHeight() {
        const otherElArr = ['#handler']
        calcScrollViewHeight(otherElArr, this, 12).then(res => {
            this.setData({
                scrollViewHeight: res
            })
        })
    },



    // switch 开关
    changePayWay(e) {
        const {
            index
        } = e.currentTarget.dataset
        const {
            value
        } = e.detail
        this.setData({
            payway: this.data.payway.map((item, idx) => {
                if (idx === index) return value

                return !value
            })
        })
    },


    //   获取收货地址
    async _getAddressList() {
        const {
            data
        } = await request({
            url: Api.getAddressList,
            method: 'POST'
        })
          if (!data.data.length) {
              this.setData({
                  addr: {}
              })
             this.freight()
          }
        data.data.map((item, index) => {
            if (item.state === 1) {
                this.setData({
                    addr: item
                })
            }
        })
        this.setData({
            addressList: data.data,
        })

          this.freight()
    },


    // 获取羊币
    async sleep_coin() {
        const {
            data
        } = await request({
            url: Api.sheep_coin,
            method: 'POST'
        })
        this.setData({
            sleep_coin: Number(data.data.sleep_coin) / 10
        })

    },




// 运费

async freight(){
    let sleep_coin = this.data.sleep_coin
    const goodlist = wx.getStorageSync("goodlist")
   let postage_money, totalMoney, remaining, deduction
     switch (this.data.gmtype) {
         case 1:
             const {data} = await request({
                 url: Api.confirmOrder,
                  data: {
                      goods_id: this.data.goodlist[0].id, //商品Id
                      price: this.data.goodlist[0].price, //商品价格
                      pay_num: 1, //购买数量
                      address_id: this.data.addr.id //收货地址ID
                  },
                  method: 'POST'
             })
            if(data.code !=2001){
                console.log(data.msg)
                WXshowToast(data.msg)
                return
            }
             postage_money = data.data.postage_money //运费
             totalMoney = Number(data.data.goods_money) + Number(postage_money)
             if (sleep_coin > totalMoney) {
                 deduction = sleep_coin 
                 remaining = sleep_coin - totalMoney
                 totalMoney = 0.00
             } else {
                 totalMoney = totalMoney - sleep_coin
                 remaining = 0.00
                 deduction = sleep_coin 
             }

             break;
        case 2:
                let cart_id = []
                for (var i = 0; i < goodlist.length; i++) {
                    cart_id.push(goodlist[i].id)
                }
                cart_id = cart_id.toString()
                const res = await request({
                    url: Api.confirmCartAll,
                    method: 'POST',
                    data: {
                        address_id: this.data.addr.id,
                        cart_id
                    }
                })
            postage_money = res.data.data.total_postage
            totalMoney = Number(res.data.data.total_money) + Number(postage_money)
            if (sleep_coin > totalMoney) {
                totalMoney = 0.00
                deduction = sleep_coin 
                remaining = sleep_coin - totalMoney
            } else {
                totalMoney = totalMoney - sleep_coin
                remaining = 0.00
                deduction = sleep_coin 
            }
     }

       this.setData({
           postage_money,
           totalMoney,
           remaining,
           deduction
       })
},


// 结算

async js(){
            const {
                     totalMoney,
                    deduction,
                    addr
             } = this.data
               if (!Object.keys(addr).length) {
                   WXshowToast("请选择收货地址")
                   setTimeout(() => {
                       WXNavigateTo("/pages/select_addr/select_addr")
                   }, 500)
                   return
               }
            console.log(addr.id)
            const openid = wx.getStorageSync("openid")
            const goodlist = wx.getStorageSync("goodlist")
            let order_no,pay
            switch (this.data.gmtype) {
                case 1:
                    console.log('商品立即购买结算')
                    const {
                        data
                    } = await request({
                        url: Api.order,
                        data: {
                            goods_id: this.data.goodlist[0].id, //商品Id
                            price: this.data.goodlist[0].price, //商品价格
                            pay_num: 1, //购买数量
                            address_id: addr.id //收货地址ID
                        },
                        method: 'POST'
                    })
                    if (data.code != 2001) {
                        WXshowToast(data.msg)
                        return
                    }
                    order_no = Object.values(data.data)[0][0].order_sn //订单编号
                    // 支付
                        console.log('totalMoney',totalMoney)
                         pay = await getWXPayOptions({
                            money: totalMoney,
                            title: "肉串礼盒",
                            order_no,
                            openid
                        })
                        // 发起微信支付
                        try {
                            const src = await requestPayment(pay.data.data.wx_pub);
                            if (src.errMsg == "requestPayment:ok") {
                                const {
                                    data
                                } = await request({
                                    url: Api.paySleepCoin,
                                    method: 'POST',
                                    data: {
                                        sleep_coin: deduction * 10 
                                    }
                                })
                            }
                            WXRedirectTo('/pages/index/index')
                        } catch (err) {
                            wx.showToast({
                                title: '支付取消',
                                icon: 'none',
                            })
                        }

                    break;

                case 2:
                    console.log("从购物车来的")
                    let cart_id = []
                    for (var i = 0; i < goodlist.length; i++) {
                        cart_id.push(goodlist[i].id)
                    }
                    cart_id = cart_id.toString()
                    const res = await request({
                        url: Api.cartAll,
                        method: 'POST',
                        data: {
                            address_id: addr.id,
                            cart_id
                        }
                    })
                    order_no = Object.values(res.data.data)[0][0].order_sn //订单编号
                //    支付
                    pay = await getWXPayOptions({
                       money: totalMoney,
                       title: "肉串礼盒",
                       order_no,
                       openid
                   })
                   // 发起微信支付
                   try {
                       const src = await requestPayment(pay.data.data.wx_pub);
                       if (src.errMsg == "requestPayment:ok") {
                           const {
                               data
                           } = await request({
                               url: Api.paySleepCoin,
                               method: 'POST',
                               data: {
                                   sleep_coin: deduction * 10
                               }
                           })
                       }
                       WXRedirectTo('/pages/index/index')
                   } catch (err) {
                       wx.showToast({
                                   title: '支付取消',
                                   icon: 'none',
                       })
                    }
            }
}
})